package com.srwl.mytx;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.activity.MainActivity;
import com.srwl.mytx.widget.ConfirmDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * 作者：lff
 * 时间；2016-4-11 14:38
 * 描述：检查更新
 */
public class UpdateManager {
    private static String TAG = UpdateManager.class.getSimpleName();
    /* 下载中 */
    private static final int DOWNLOADING = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    //判断是否更新中
    public static String tag = "1";//未点击更新
    private InteractionInterface interactionInterface;

    /* 下载保存路径 */
    private String mSavePath;
    private static String apkName = "mytx.apk";
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private int serviceVersionCode;//版本号
    private String urlapk;//apk地址
    private String notes;//升级说明
    private Context mContext;
    private int len;
    private NotificationManager manager;
    private Notification notif;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    //    RemoteViews contentView;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOADING:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    //  progress, false);
                    notif.contentView.setTextViewText(R.id.content_view_text1, progress + "%");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, progress, false);
                    manager.notify(1, notif);
                    // downloadNotif();
                    break;
                case DOWNLOAD_FINISH:
                    //mDownloadDialog.dismiss();
                    // 安装文件
//                     notif.contentView.setTextViewText(R.id.content_view_text1, "下载完成！");
//                     notif.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
//                      manager.notify(0, notif);
                    manager.cancel(1);
                    tag = "2";//更新完成开始安装
                    installApk();

                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(int versionCode, String url, String notes, Context context) {
        this.mContext = context;
        this.serviceVersionCode = versionCode;
        this.urlapk = url;
        this.notes = notes;

    }

    public boolean isShowToast = true;

    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        if (isUpdate()) {
            // 显示更新对话框
            showNoticeDialog();
        } else {
            if (interactionInterface != null) {
                interactionInterface.showToast("当前版本已经是最新版本");
            }

        }
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate() {
        // 获取当前软件版本
        int versionCode = getVersionCode(mContext);


        // 版本判断
        if (serviceVersionCode > versionCode) {
            return true;
        }

        return false;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        Builder builder = new Builder(mContext);
        builder.setTitle("版本更新");
        builder.setMessage(notes);
        // 更新
        builder.setPositiveButton("更新", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (interactionInterface != null) {
                    interactionInterface.showToast("后台更新中,请稍后...");
                } else {
                    showToast(mContext, "后台更新中,请稍后...");
                }

                tag = "3";//开始更新
                // 显示下载对话框
                showDownloadDialog();
            }
        });
        // 稍后更新
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(mContext.getResources().getColor(R.color.text_black));
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {

        // 构造软件下载对话框
        Builder builder = new Builder(mContext);
        builder.setTitle("下载中");
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        //  mDownloadDialog.show();   //不显示下载对话框
        String channelID = "update";
        //点击通知栏后打开的activity
        manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        final RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.softupdate_notify_layout);
        remoteViews.setProgressBar(R.id.content_view_progress, 100, 0, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelID, "版本更新", NotificationManager.IMPORTANCE_HIGH); //8.0 系统需要设置 通道
            manager.createNotificationChannel(channel);
            final Notification.Builder notifyBuilder = new Notification.Builder(mContext, channelID)
                    .setSmallIcon(R.drawable.app_icon)
                    .setCustomContentView(remoteViews)
                    .setAutoCancel(false);
            notif = notifyBuilder.build();
            manager.notify(1, notif);

        } else {

//            Intent intent = new Intent(mContext, MainActivity.class);
//            PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            final NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(mContext, channelID)
                    .setChannelId(channelID)
                    .setSmallIcon(R.drawable.app_icon)
                    .setCustomContentView(remoteViews)
                    .setAutoCancel(false);
            notif = notifyBuilder.build();
            manager.notify(1, notif);

        }
        // 下载文件
        downloadApk();
    }

    /*表示下下载进度的通知*/
    public void downloadNotif() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, "mytx_update");
        builder.setSmallIcon(R.mipmap.ic_launcher);//显示的小图标
        builder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher));//下拉现实的额大图表
        //禁止用户点击数删除
        builder.setAutoCancel(false);
        //取消时间的显示
        builder.setShowWhen(false);
        //禁止滑动删除
        builder.setOngoing(true);
        builder.setProgress(100, progress, false);
        Notification notification = builder.build();
        manager.notify(1, notification);
    }

    public void nomaleNotif() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, "mytx_update");
        builder.setTicker("提示");
        builder.setContentTitle("标题");
        builder.setSubText("摘要");
        builder.setContentText("内容");
        builder.setContentInfo("显示于通知时间的下面");
        builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
        builder.setNumber(1);//显示同种通知的数量，塔河setContentinfo只能设置其中一种
        builder.setAutoCancel(true);//可以点击通知栏的删除按钮删除
        builder.setSmallIcon(R.mipmap.ic_launcher);//显示的小图标
        builder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher));//下拉现实的额大图表
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 1, new Intent(mContext, MainActivity.class), 0);//点击实现跳转
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();
        manager.notify(1, notification);
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件

        new downloadApkThread().start();
    }

    int downloadCount = 0;

    protected void showToast(Context context, final String toastContent) {
        Snackbar.make(((Activity) context).getWindow().getDecorView(), toastContent, Snackbar.LENGTH_LONG).show();

    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {

                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    mSavePath = mContext.getExternalCacheDir().getAbsolutePath() + File.separator;

                    URL url = new URL(urlapk);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, apkName);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中


                    do {
                        int numRead = is.read(buf);
                        count += numRead;

                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        Log.i(TAG, "progress===" + progress);
                        Log.i(TAG, "count===" + count + numRead);
                        // 更新进度
                        //为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                        if (downloadCount == 0 || progress - 5 > downloadCount) {
                            downloadCount += 5;
                            mHandler.sendEmptyMessage(DOWNLOADING);
                        }
                        if (numRead <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            Log.d(TAG, "下载完成");
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numRead);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk() {

        Log.d(TAG, "准备安装apk");
        File apkfile = new File(mSavePath + File.separator + apkName);
        // ApkUtils.installAPk(mContext,apkfile);
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uri = FileProvider.getUriForFile(mContext, "com.srbl.mytx.fileProvider", apkfile);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {

            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);


    }

    public void setInteractionInterface(InteractionInterface interactionInterface) {
        this.interactionInterface = interactionInterface;
    }

    public interface InteractionInterface {
        void showToast(String content);
    }
}
